package com.hui.server.exception;

import com.hui.server.util.Result;
import com.mysql.cj.log.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @BelongsProject: yeb
 * @BelongsPackage: com.hui.server.exception
 * @Author: HUI
 * @CreateTime: 2022-04-04 18:17
 * @Description:
 */

@RestControllerAdvice
@Slf4j
public class GlobalException {


    @ExceptionHandler(SQLException.class)
    public Result<Exception> mySQLException(SQLException e){

        if (e instanceof SQLIntegrityConstraintViolationException){
            log.error("数据库外键异常：{}",e.getMessage());
            return Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()),"该数据有关联数据，操作失败！");
        }

        log.error("数据库异常：{}",e.getMessage());
        return Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()),"数据库异常，操作失败！");
    }

    @ExceptionHandler(NullPointerException.class)
    public Result<Exception> myNullPointerException(NullPointerException e){
        log.error("空指针异常：{}",e.getMessage());
        e.printStackTrace();

        return Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()),"数据出现异常，空指针异常："+e.getMessage());
    }

}
